package com.project.controller.home;

import com.alibaba.fastjson.JSON;
import com.project.controller.base.BaseController;
import com.project.model.Topics;
import com.project.service.TopicsService;
import com.project.service.UserService;
import com.project.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private TopicsService topicsService;

    @RequestMapping(value = {"topics", "/"})
    public String topics() {
        return "home/topics";
    }

    @ResponseBody
    @PostMapping("getTopics")
    public String getTopics(@RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "pageSize", defaultValue = "10") int size) {
        List<Topics> topics = topicsService.selectAll(start, size);
        List<Map> newTopics = new ArrayList<>();
        for (Topics topic : topics) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", topic.getId());
            map.put("title", topic.getTitle());
            map.put("likeNum", topic.getLikeNum());
            map.put("commentNum", topic.getCommentNum());
            map.put("pv", topic.getPv());
            String lastCommentAt = topic.getLastCommentAt();
            long lastCommentTime = 0l;
            if (lastCommentAt != null) {
                lastCommentTime = Util.strToTime("yyyy-MM-dd HH:mm:ss", topic.getLastCommentAt());
            }
            map.put("lastCommentAt", (System.currentTimeMillis() - lastCommentTime) / 1000 / 60 / 60);
            newTopics.add(map);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("content", newTopics);
        map.put("currentPage", start);
        map.put("totalPage", Math.round(topicsService.count() / size));
        return JSON.toJSONString(map);
    }
    @GetMapping("/topics/{id}")
    public String topicsDetail(Model model,@PathVariable("id") int id) {
        Topics topics = topicsService.selectByPrimaryKey(id);
        model.addAttribute("content",topics.getContent());
        model.addAttribute("id",id);
        return "home/topicsDetail";
    }
}
